package com.eques.util;

import android.text.TextUtils;

import com.eques.icvss.utils.ELog;

import org.apache.commons.lang3.StringUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringHandler {

    /**
     * 根据分隔符截取字符串
     *
     * @param str       字符串
     * @param separator 分隔符
     * @return 截取的字符串数组
     */
    public static String[] split(String str, String separator) {
        if (TextUtils.isEmpty(str) || TextUtils.isEmpty(separator)) {
            return null;
        }
        int index;
        ArrayList<String> list = new ArrayList<>();
        String[] strings = null;
        while ((index = str.indexOf(separator)) != -1) {
            list.add(str.substring(0, index));
            str = str.substring(index + separator.length());
        }
        list.add(str);

        if (list.size() > 0) {
            strings = new String[list.size()];
        }
        return list.toArray(strings);
    }

    /**
     * 使用StringBuffer追加字符串
     *
     * @param str 字符串数组
     * @return 完整字符串
     */
    public static String append(String... str) {
        StringBuilder sb = new StringBuilder();
        for (String s : str) {
            if (null != s) {
                sb.append(s);
            }
        }
        return sb.toString();
    }

    private static final String MSG_REPLACE_STR = "%s";

    public static String replace(String src, String... str) {
        try{
            if (str == null) {
                return src;
            }
            int count = countStr(src, MSG_REPLACE_STR);
            if (count != str.length) {
                return null;
            }

            for (String s : str) {
                src = src.replaceFirst(MSG_REPLACE_STR, s);
            }
            return src;
        }catch (Exception e){
            e.printStackTrace();
        }
      return "";
    }

    /**
     * 计算src中包含str的个数
     * 可以优化 --> indexOf(a, b)
     */
    private static int countStr(String src, String str) {
        int count = 0;
        if (src.contains(str)) {
            count += countStr(src.substring(src.indexOf(str) + str.length()), str);
            return count + 1;
        }
        return 0;
    }

    /**
     * 去除字符串中的空格、回车、换行符、制表符
     */
    public static String replaceBlank(String str) {
        String dest = "";

        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * 将二进制数据转换为文件
     */
    public static void data2file(byte[] data, String fileName) {
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(fileName);
            out.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 对字符串加密,加密算法使用MD5,SHA-1,SHA-256,默认使用SHA-256
     *
     * @param phoneNum    要加密的字符串
     * @param smsCode    要加密的字符串
     * @param encName    加密类型
     * hint = SHA256(PHONE + SMS_CODE + SALT)
     */
    private static final String SALT = "EEU0lnSakypQBKoCMydhdsDNAR36dAAA";

    public static String EncryptStrData(String phoneNum, String smsCode, String encName) {
        if (StringUtils.isBlank(phoneNum) || StringUtils.isBlank(smsCode)) {
            return null;
        }

        String strSrc = phoneNum + smsCode + SALT;
        //ELog.e(" StringHandler: ", " before-->strSrc: ", strSrc);
        MessageDigest md;
        String strDes;
        byte[] bt = strSrc.getBytes();
        try {
            if (TextUtils.isEmpty(encName)) {
                encName = "SHA-256";
            }
            md = MessageDigest.getInstance(encName);
            md.update(bt);
            strDes = bytes2Hex(md.digest()); // to HexString
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        //ELog.e(" StringHandler: ", " after-->strSrc: ", strSrc);
        return strDes;
    }

    private static String bytes2Hex(byte[] bts) {
        StringBuilder des = new StringBuilder();
        String tmp;
        for (byte bt : bts) {
            tmp = (Integer.toHexString(bt & 0xFF));
            if (tmp.length() == 1) {
                des.append("0");
            }
            des.append(tmp);
        }
        return des.toString();
    }

    /**
     * 检测是否有emoji表情
     *
     * @param source
     * @return
     */
    public static boolean containsEmoji(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!isEmojiCharacter(codePoint)) {
                // 如果不能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }

    public static boolean strIsEmpty(String str) {
        if (str == null || TextUtils.isEmpty(str) || "".equals(str)) {
            // 先判断是不是对象，如果是，再判断是不是空字符串
            return true;
        }
        // 判断一个字符串是否为空，首先就要确保他不是null，然后再判断他的长度
        return str.length() == 0;
    }

    /**
     * 判断是否是Emoji
     *
     * @param codePoint 比较的单个字符
     * @return
     */
    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) ||
                (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000)
                && (codePoint <= 0x10FFFF));
    }

    public static void printLog(String b, String u) {
        if (!strIsEmpty(b)) {
            ELog.e("lg rst", " b ", b);
        }
        if (!strIsEmpty(u)) {
            ELog.e("lg rst", " u ", u);
        }
    }

    /**
     * 字符串转UTF-8格式
     * json数据转换
     *
     * @param str
     * @return
     */
    public static String strToJsonByUtf8(String str) {
        String result = null;
        result = new String(str.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
        return result;
    }

    /**
     * 字符串转UTF-8格式
     * url转换
     *
     * @param str
     * @return
     */
    public static String strToUrlByUtf8(String str) {
        String result = null;
        try {
            result = URLDecoder.decode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

}
